package top.houry.netty.barrage.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import top.houry.netty.barrage.consts.BarrageRedisKeyConst;
import top.houry.netty.barrage.utils.BarrageRedisUtils;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;


@Slf4j
public class WebSocketNettyServerJoinInBlackListHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取发送的消息
     *
     * @param ctx     通道上下文
     * @param barrage 信息内容
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object barrage) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        String count = BarrageRedisUtils.get(BarrageRedisKeyConst.BARRAGE_SERVER_FLOW_CONTROL_KEY + clientIp);
        if (Integer.parseInt(count) > 100) {
            BarrageRedisUtils.set(BarrageRedisKeyConst.BARRAGE_SERVER_REJECT_CONNECT_KEY + clientIp, clientIp, 365L, TimeUnit.DAYS);
            log.info("WebSocketNettyServerJoinInBlackListHandler-channelRead-ip:{}-已经加入黑名单", clientIp);
            ctx.channel().close();
        } else {
            ctx.fireChannelRead(barrage);
        }
    }
}
